import {ModalForm, ProFormSelect, ProFormText} from '@ant-design/pro-components';
import nginxServices from '@/services/nginx';
import {Form} from 'antd';
import {useEffect, useState} from 'react';

export interface FormValueType extends Partial<API.SettingAccess> {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
}


export interface EditFormProps {
  onOpenChange: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  editModalVisible: boolean;
  values: Partial<API.SettingAccess>;
  accessEnum?: Partial<Record<string, { text: string; status: string }>>;
}


export default (props:EditFormProps) => {
  const [form] = Form.useForm();
  const [options, setOptions] = useState<{ label: string; value: string; }[]>([]);


  const fetchOptions = async () => {
    try {
      const response = await nginxServices.CloudAccessKeyController.accessKeys();
      if (response && response.data) {
        const newOptions = response.data.map((item) => ({
          label: item.name,
          value: String(item.accessId), // 确保 value 是字符串类型
        }));
        setOptions(newOptions);
        return newOptions;
      }
      return [];
    } catch (error) {
      console.error('Failed to fetch webhook list:', error);
      return [];
    }
  };
  useEffect(() => {
    fetchOptions();
  }, []);


  useEffect(() => {
    if (props.values.accessId !== undefined) {
      form.setFieldsValue({
        webhookId: props.values.accessId
      });
    }
  }, [props.values.accessId, form]);



  return (
      <ModalForm
        title= {props.values.accessId === null ? "设置access": '修改access'}
        open={props.editModalVisible}
        onOpenChange={props.onOpenChange}
        onFinish={props.onSubmit}
        initialValues={props.values}
        form={form}
    >
       <ProFormText
        width="md"
        name="id"
        label="Id"
        hidden={true}
        disabled={true}
      />
      <ProFormSelect
        width="md"
        name="accessId"
        options={options}
        fieldProps={{
          onChange: (value) => {
            form.setFieldsValue({ accessId: value });
          },
        }}
      />
    </ModalForm>
  );
};
